from fastapi import FastAPI, HTTPException, APIRouter
from pydantic import BaseModel, Field
from datetime import datetime
from typing import List, Optional
import uvicorn

# 假设这是导入的成绩表模块（示例中未使用，保留引用）
# from day2.成绩表 import StudentScore

app04 = APIRouter()


class Student(BaseModel):
    stu_id: str = Field(..., description="学生ID")
    # 将kq改为datetime类型，更符合考勤时间的语义
    kq: datetime = Field(..., description="考勤时间")
    bulu: int = Field(0, ge=0, le=1, description="是否补录，0-否，1-是")


# 初始化数据（注意：原数据中有重复的stu_id，实际业务中可能需要避免）
students = [
    {"stu_id": "23051804", "kq": "2024-03-11T08:57:00", "bulu": 0},
    {"stu_id": "23051804", "kq": "2024-03-12T08:57:00", "bulu": 0},
    {"stu_id": "23051802", "kq": "2024-03-11T09:00:00", "bulu": 1}
]


@app04.get("/student", response_model=List[Student])
async def get_students():
    """查询所有学生考勤信息"""
    return students


@app04.get("/student_id/{stu_id}", response_model=List[Student])
async def get_id_student(stu_id: str):
    """通过ID查询学生的所有考勤记录（支持一个学生多条记录）"""
    # 查找所有匹配的记录（原逻辑只返回第一条，改为返回列表更合理）
    matched_students = [s for s in students if s["stu_id"] == stu_id]
    if not matched_students:
        raise HTTPException(status_code=404, detail="Student not found")
    return matched_students


@app04.post("/add_student", response_model=Student)
async def add_student(student: Student):
    """添加学生考勤信息"""
    # 修复变量名冲突和判断逻辑：检查是否已存在相同ID的记录
    for s in students:
        if s["stu_id"] == student.stu_id:
            # 这里根据业务需求：如果允许同一学生多条记录可删除此判断
            raise HTTPException(status_code=400, detail=f"ID {student.stu_id} 已存在")

    # 将新学生信息添加到列表（放在循环外部）
    students.append(student.dict())
    return student


@app04.put("/update_student/{stu_id}", response_model=Student)
async def mod_student(stu_id: str, new_student: Student):
    """修改学生考勤信息（根据stu_id更新对应记录）"""
    for index, stu in enumerate(students):
        if stu['stu_id'] == stu_id:
            # 替换为新数据（字典格式）
            students[index] = new_student.dict()
            return new_student  # 返回更新后的模型
    raise HTTPException(status_code=404, detail=f"学生ID {stu_id} 未找到，无法修改")


@app04.delete("/delete_student/{stu_id}")
async def delete_student(stu_id: str):
    """删除学生所有考勤记录"""
    # 收集所有匹配的索引（支持删除同一学生的多条记录）
    to_delete_indices = [i for i, s in enumerate(students) if s["stu_id"] == stu_id]

    if not to_delete_indices:
        raise HTTPException(status_code=404, detail=f"学生ID {stu_id} 未找到，无法删除")

    # 从后往前删除（避免索引偏移）
    for i in reversed(to_delete_indices):
        del students[i]

    return {"message": "删除成功", "deleted_stu_id": stu_id, "deleted_count": len(to_delete_indices)}
